package com.example.myapplication.ui

import android.Manifest.permission.MANAGE_EXTERNAL_STORAGE
import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.Manifest.permission.READ_MEDIA_VIDEO
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.myapplication.Constants
import com.example.myapplication.R
import com.example.myapplication.ad.InterstitialAdManager
import com.example.myapplication.ad.Location
import com.example.myapplication.appViewModel
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.extensions.showNormalDialog
import com.example.myapplication.utils.SPUtils
import com.example.myapplication.view.CommonDialog
import com.example.myapplication.viewmodel.ApiViewModel
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.example.myapplication.adapter.MainAdapter
import com.example.myapplication.adapter.MainAdapter.Companion.TYPE_1
import com.example.myapplication.adapter.MainAdapter.Companion.TYPE_2
import com.example.myapplication.adapter.MainAdapter.Companion.TYPE_3


class MainActivity : AppCompatActivity() {
    private val viewModel by viewModels<ApiViewModel>()
    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding
    private lateinit var adManager: InterstitialAdManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        if (SPUtils.getBooleanValue("hasOpened")) {
            if (SPUtils.getBooleanValue("hasAllGranted")) {
              //  requestPermissionX()
            }
            adManager = InterstitialAdManager(this).apply {
                loadAd(Location.A10002)
            }
        } else {
            SPUtils.setKeyValue("hasOpened", true)
           // showPermissionDialog()
        }

        val adapter = MainAdapter(supportFragmentManager)
        binding.viewPager.adapter = adapter
        binding.viewPager.offscreenPageLimit = adapter.count

        val tabs = arrayOf(binding.rbCalendar.id,binding.rbCollect.id,binding.rbMine.id)
        binding.radioGroup.setOnCheckedChangeListener { _, i ->
            when (i) {
                tabs[0] -> {
                    binding.viewPager.currentItem = TYPE_1
                }

                tabs[1] -> {
                    binding.viewPager.currentItem = TYPE_2
                }
                tabs[2] -> {
                    binding.viewPager.currentItem = TYPE_3
                }
            }
        }

        upgradeApp()
    }

    private fun upgradeApp() {
        val launchData = appViewModel.launchData.value
        if (launchData == null || launchData.update?.note.isNullOrEmpty()) {
            return
        }
        CommonDialog.Companion.show(
            context = this,
            isCancelable = launchData.update?.force != true,
            config = CommonDialog.Config(
                icon = ContextCompat.getDrawable(this, R.mipmap.icon),
                content = launchData.update?.note,
                positiveText = getString(R.string.download),
                wrapContent = true,
                negativeText = null,
                onPositiveClick = {
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.setData(launchData.update?.url?.toUri())
                    startActivity(intent)
                }
            )
        )
    }


    fun showPermissionDialog() {
        showNormalDialog(
            this,
            null,
            "用户您好：本应用需要获取您手机的存储权限，用于读取相册中的视频文件并为您提供本地相册视频播放服务。"
        ) {
            requestPermissionX()
        }
    }

    fun requestPermissionX() {
        val permissions = if (Build.VERSION.SDK_INT >= 33) {
            listOf(READ_MEDIA_VIDEO)
        } else if (Build.VERSION.SDK_INT >= 30) {
            listOf(MANAGE_EXTERNAL_STORAGE)
        } else {
            listOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE)
        }

        XXPermissions.with(this)
            .permission(Permission.READ_MEDIA_VIDEO)
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        Toast.makeText(this@MainActivity, "获取部分权限成功，但部分权限未正常授予！", Toast.LENGTH_LONG)
                            .show()
                        return
                    }
                    SPUtils.setKeyValue("hasAllGranted", true)
                    viewModel.getVideoFolders()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        Toast.makeText(this@MainActivity, "被永久拒绝授权，请手动授予存储权限！", Toast.LENGTH_LONG)
                            .show()
                        //XXPermissions.startPermissionActivity(this@MainActivity, permissions)
                    } else {
                        Toast.makeText(this@MainActivity, "获取存储权限失败！", Toast.LENGTH_LONG).show()
                    }
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        adManager.destroyAD()
    }
}